package demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;


import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;




@ManagedBean(name = "uploaderBB")
public class FileUploadController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	public FileUploadController(){
		System.out.println("FileUploadController创建了");
	}
	
	public void handleFileUpload(FileUploadEvent event){

		InputStream inputStream = null;
		OutputStream  outputSream = null;
		try{
			
		
			
			UploadedFile uploadFile = event.getFile();
			String fileName = uploadFile.getFileName();
			inputStream = uploadFile.getInputstream();
			
			//获取工程的绝对路径，如工程的绝对路径：D:\apache-tomcat-7.0.21\webapps\jsf2\
			String projectAbsolutePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
			System.out.println("工程的绝对路径："+projectAbsolutePath);
			
			//将要写入文件的写入绝对路径，如写入文件的绝对路径：D:\\apache-tomcat-7.0.21\\webapps\\jsf2\\upload\
			//注意这里的路径是打包到Tomcat，解压缩后文件夹的路径，而不是以源代码的路径来看待
			//所以，这里不再添加WebContent
			String fileAbsolutePath = projectAbsolutePath+"upload\\";//此处的“\\”可以写，可以不写
			System.out.println("写入文件的绝对路径："+fileAbsolutePath);
			
			
			File target_folder = new File(fileAbsolutePath);
			outputSream = new FileOutputStream(new File(target_folder, fileName));
			
			int read = 0;
			byte[] size = new byte[1024];
			while((read = inputStream.read(size)) != -1){
				outputSream.write(size, 0, read);
			}
			
			outputSream.flush();
			outputSream.close();
			inputStream.close();
			
		
			
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			
			
			try {
				
				if(outputSream!=null){
					outputSream.flush();
					outputSream.close();
				}
				
				
				if(inputStream!=null){
					inputStream.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	

}
